package com.axend.aerosense.room.ui.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.impl.IComplete;
import com.axend.aerosense.common.bean.PersonSelectItemBean;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.room.entity.PhoneAreaCodeBean;
import com.blankj.utilcode.util.FragmentUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.axend.aerosense.base.activity.MvvmBaseActivity;
import com.axend.aerosense.base.viewmodel.BaseViewModel;
import com.axend.aerosense.common.adapter.ScreenAutoAdapter;
import com.axend.aerosense.common.bean.WardSelectItemBean;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.util.FragmentUtil;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomActivityAddRoomBinding;
import com.axend.aerosense.room.ui.fragment.RoomPersonSelectFragment;
import com.axend.aerosense.room.ui.fragment.RoomPersonSettingFragment;
import com.axend.aerosense.room.ui.fragment.RoomWardSettingFragment;
import com.axend.aerosense.room.ui.fragment.RoomSettingFragment;
import com.axend.aerosense.room.ui.fragment.RoomWardSelectFragment;

/**
 * @author 房间新增设定界面承载主体
 * @date :2020/12/29 14:59
 */
@Route(path = RouterActivityPath.Room.PAGE_ROOM_PICKER)
public class PeoplePickerActivity extends MvvmBaseActivity<RoomActivityAddRoomBinding, BaseViewModel> {
    public final static int OPEN_TYPE_WARD = 1;
    public final static int OPEN_TYPE_PERSON = 2;

    @Autowired
    int openType = OPEN_TYPE_WARD;

    boolean selectMode = false;

    private String uid = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ScreenAutoAdapter.match(this, 375.0f);
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        openType = getIntent().getIntExtra(Gobal.CLASS_KEY.OPEN_TYPE_KEY, OPEN_TYPE_WARD);
        selectMode = getIntent().getBooleanExtra(Gobal.CLASS_KEY.SELECT_MODE_KEY, false);
        uid = getIntent().getStringExtra(Gobal.CLASS_KEY.OBJECT_UID_KEY);

        ImmersionBar.with(this)
                .statusBarColor(android.R.color.white)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true)
                .autoDarkModeEnable(true).init();
        setSupportActionBar(viewDataBinding.roomToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);//左侧添加一个默认的返回图标
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        getSupportFragmentManager().addOnBackStackChangedListener(getListener());
        if (OPEN_TYPE_WARD == openType) {
            bindFragment(RoomWardSelectFragment.getInstance(selectMode, uid));

        } else if (OPEN_TYPE_PERSON == openType) {
            bindFragment(RoomPersonSelectFragment.getInstance(selectMode, uid));

        }
        if (selectMode) {
            setRightTitle(getString(R.string.common_complete));
        } else {
            setRightTitle("");
        }

        viewDataBinding.roomToolbar.setSettingTextOnClickListener(v->{
            FragmentManager manager = getSupportFragmentManager();
            Fragment currFrag = manager.findFragmentById(getContentId());
            if(currFrag instanceof IComplete){
                ((IComplete) currFrag).complete();
            }
        });
    }

    private FragmentManager.OnBackStackChangedListener getListener() {
        FragmentManager.OnBackStackChangedListener result = () -> {
            FragmentManager manager = getSupportFragmentManager();
            if (manager != null) {
                Fragment currFrag = (Fragment) manager.findFragmentById(getContentId());
                currFrag.onResume();
            }
        };

        return result;
    }

    private void bindFragment(Fragment fragment) {
        FragmentUtil.add(this, viewDataBinding.roomContent.getId(), fragment, null, false);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(null != this.getCurrentFocus()){
            /**
             * 点击空白位置 隐藏软键盘
             */
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
            if(selectMode){
                Fragment currFrag = (Fragment) getSupportFragmentManager().findFragmentById(getContentId());
                if(currFrag instanceof RoomPersonSelectFragment || currFrag instanceof RoomWardSelectFragment){
                    ((IComplete)currFrag).complete();
                    return;
                }
            }

            finish();
            return;
        }
        FragmentUtils.show(getSupportFragmentManager());
        super.onBackPressed();
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_activity_add_room;
    }

    @Override
    public int getBindingVariable() {
        return 0;
    }

    @Override
    protected BaseViewModel getViewModel() {
        return null;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    public void setTitle(String title) {
        viewDataBinding.roomTitle.setText(title);
    }

    public void setRightTitle(String title) {
        viewDataBinding.roomToolbar.setMySettingText(title);
        if (!TextUtils.isEmpty(title)) {
            viewDataBinding.roomToolbar.setRightTitleVisibility(View.VISIBLE);
        } else {
            viewDataBinding.roomToolbar.setRightTitleVisibility(View.GONE);
        }
    }

    public void setRightTitleClickable(boolean clickable) {
        if(clickable){
            viewDataBinding.roomToolbar.setMySettingTextColor(getResources().getColor(R.color.common_item_selector, null));
        }else{
            viewDataBinding.roomToolbar.setMySettingTextColor(getResources().getColor(R.color.common_btn_pressed_color_gray, null));
        }
        viewDataBinding.roomToolbar.setRightTitleClickable(clickable);
    }


    public int getContentId() {
        return viewDataBinding.roomContent.getId();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (data == null) {
            return;
        }
        if (requestCode == RoomSettingFragment.REQUEST_PERSON) {
            RoomSettingFragment fragment = (RoomSettingFragment) getSupportFragmentManager().findFragmentByTag(RoomSettingFragment.class.getSimpleName());
            fragment.setPerson((PersonSelectItemBean) data.getSerializableExtra(RoomPersonSelectFragment.SELECT_PERSON));

        } else if (requestCode == RoomSettingFragment.REQUEST_WARD) {
            RoomSettingFragment fragment = (RoomSettingFragment) getSupportFragmentManager().findFragmentByTag(RoomSettingFragment.class.getSimpleName());
            fragment.setWard((WardSelectItemBean) data.getSerializableExtra(RoomWardSelectFragment.SELECT_WARD));

        } else if(requestCode == PhoneCodePieckerActivity.PERSON_REQUEST_CODE){
            RoomPersonSettingFragment fragment = (RoomPersonSettingFragment) getSupportFragmentManager().findFragmentByTag(RoomPersonSettingFragment.class.getSimpleName());
            fragment.setPhoneCode((PhoneAreaCodeBean) data.getSerializableExtra(PhoneCodePieckerActivity.PARAM_KEY));

        } else if(requestCode == PhoneCodePieckerActivity.WARD_REQUEST_CODE){
            RoomWardSettingFragment fragment = (RoomWardSettingFragment) getSupportFragmentManager().findFragmentByTag(RoomWardSettingFragment.class.getSimpleName());
            fragment.setPhoneCode((PhoneAreaCodeBean) data.getSerializableExtra(PhoneCodePieckerActivity.PARAM_KEY));
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}
